package net.gazhi.delonix.core.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * RequestMappingHandlerMapping 持有者<br>
 * 请在 Root ApplicationContext 定义此Bean
 * 
 * @author Jeffrey Lin
 * 
 */
public class RequestMappingHandlerMappingHolder {

	private List<RequestMappingHandlerMapping> mps = new ArrayList<RequestMappingHandlerMapping>();

	public void add(RequestMappingHandlerMapping mp) {
		mps.add(mp);
	}

	public void remove(RequestMappingHandlerMapping mp) {
		mps.remove(mp);
	}

	/**
	 * 根据uri路径查找匹配执行该路径的方法
	 * 
	 * @param uriPattern
	 * @param methods
	 * @return
	 */
	public HandlerMethod machMethod(String uriPattern) {
		Map<RequestMappingInfo, HandlerMethod> methods = getHandlerMethods();
		for (RequestMappingInfo info : methods.keySet()) {
			for (String pattern : info.getPatternsCondition().getPatterns()) {
				if (pattern.equals(uriPattern)) {
					HandlerMethod method = methods.get(info);
					return method;
				}
			}
		}
		return null;
	}

	/**
	 * 获取所有 Servlet 的请求处理方法映射
	 * 
	 * @return
	 */
	public Map<RequestMappingInfo, HandlerMethod> getHandlerMethods() {
		Map<RequestMappingInfo, HandlerMethod> methods = new HashMap<RequestMappingInfo, HandlerMethod>();
		for (RequestMappingHandlerMapping mp : mps) {
			methods.putAll(mp.getHandlerMethods());
		}
		return methods;
	}

}
